package com.yfbao.web.gateway.ops;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.yfbao.web.gateway.config.OpsUrlConfig;
import com.yfbao.web.gateway.utils.CommonUtil;
import com.yfbao.web.gateway.vo.TokenResponseVo;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

//@Service
@Slf4j
public class AuthService {

//    private final OkHttpClient client;
//    private final ObjectMapper objectMapper;
    private final ObjectMapper objectMapper = new ObjectMapper();

    private String authUrl="/token";
    private String clientSecret="";
    private String clientId="";
    private String baseUrl="";

    public static Cache<String, TokenResponseVo> tokenCache = Caffeine.newBuilder().expireAfterWrite(2, TimeUnit.HOURS)
            .maximumSize(10)
            .recordStats().build();


    public AuthService() {
//        this.client = client;
//        this.objectMapper = objectMapper;
        this.authUrl = OpsUrlConfig.tokenUrl;
        this.clientId = OpsUrlConfig.clientId;
        this.clientSecret = OpsUrlConfig.clientSecret;
        this.baseUrl = OpsUrlConfig.baseUrl;
    }

    /**
     * 获取Token
     * todo： 从数据库读取ops配置，获取到 地址和密钥信息
     */
    public TokenResponseVo acquireToken() throws IOException {
        TokenResponseVo ifPresent = tokenCache.getIfPresent(this.authUrl);
        if(ifPresent != null) {
            return ifPresent;
        }

        return refreshToken();
    }

    @NotNull
    public TokenResponseVo refreshToken() throws IOException {
        OkHttpClient client = new OkHttpClient();
        // 构造JSON请求体
        Map<String, String> requestBodyMap = new HashMap<>();
        requestBodyMap.put("username", clientId);
        requestBodyMap.put("password", clientSecret);
        requestBodyMap.put("type", "account");

        String jsonBody = objectMapper.writeValueAsString(requestBodyMap);
        RequestBody requestBody = RequestBody.create(MediaType.get("application/json; charset=utf-8"),jsonBody);

        Request request = new Request.Builder()
                .url(CommonUtil.buildUrl(baseUrl, authUrl))
                .post(requestBody)
                .header("Content-Type", "application/json")
                .build();

        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new RuntimeException("认证失败: " + response.code() + " - " + response.message());
            }

            ResponseBody body = response.body();
            if (body == null) {
                throw new RuntimeException("认证响应体为空");
            }

            String responseText = body.string();
            log.debug("认证响应: {}", responseText);
            TokenResponseVo tokenResponse = objectMapper.readValue(responseText, TokenResponseVo.class);
            tokenCache.put(this.authUrl, tokenResponse);
            return tokenResponse;
        }
    }

//    /**
//     * 验证Token
//     */
//    public boolean validateToken(String token) {
//        if (StrUtil.isBlank(token)) {
//            return false;
//        }
//
//        Request request = new Request.Builder()
//                .url(authUrl + "/validate")
//                .header("Authorization", "Bearer " + token)
//                .get()
//                .build();
//
//        try (Response response = okHttpClient.newCall(request).execute()) {
//            return response.isSuccessful();
//        } catch (IOException e) {
//            log.warn("Token验证请求失败: {}", e.getMessage());
//            return false;
//        }
//    }






}